<?php

namespace app\admin\model\scanwork;

use think\Model;

class StockTransaction extends Model
{
    protected $name = 'scanwork_stock_transaction';
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function details()
    {
        return $this->hasMany('StockTransactionDetail', 'transaction_id', 'id');
    }

    public function sourceWarehouse()
    {
        return $this->belongsTo('Warehouse', 'source_warehouse_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function targetWarehouse()
    {
        return $this->belongsTo('Warehouse', 'target_warehouse_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function generateTransactionNo($type)
    {
        $prefix = [
            1 => 'CG',  // 采购入库
            2 => 'SC',  // 生产入库
            3 => 'QT',  // 其他入库
            4 => 'XS',  // 销售出库
            5 => 'LL',  // 生产领料
            6 => 'QC',  // 其他出库
            7 => 'DB',  // 调拨
            8 => 'PD',  // 盘点
        ];
        
        $date = date('Ymd');
        $pre = $prefix[$type] ?? 'TR';
        
        $lastNo = self::where('transaction_no', 'like', $pre . $date . '%')
            ->order('id', 'desc')
            ->value('transaction_no');
        
        if ($lastNo) {
            $lastNum = intval(substr($lastNo, -4));
            $newNum = str_pad($lastNum + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $newNum = '0001';
        }
        
        return $pre . $date . $newNum;
    }
}

